package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaContans;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import io.seata.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    private String url;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile==null|| StringUtils.isBlank(multipartFile.getOriginalFilename()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        try {
            String fileId = fastDFSClient.uploadFile(multipartFile);
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(fileId);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);
            wmMaterial.setUrl(url+fileId);
            return ResponseResult.okResult(wmMaterial);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传失败");
        }
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null ||user.getId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        boolean b = update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, type).eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId()));
        if (!b)
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if (id==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null||user.getId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        Integer i = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (i!=null && i>0)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"该素材被引用，不能删除");

        WmMaterial wmMaterial = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId()));
        if (wmMaterial==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        fastDFSClient.delFile(wmMaterial.getUrl());
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        dto.checkParam();
        Page page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, user.getId());
        if (dto.getIsCollected()!=null && dto.getIsCollected().equals(WemediaContans.COLLECT_MATERIAL)){
            queryWrapper.eq(WmMaterial::getIsCollection,WemediaContans.COLLECT_MATERIAL);
        }
        IPage<WmMaterial> iPage = page(page, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        List<WmMaterial> list = iPage.getRecords().stream().map(item -> {
            item.setUrl(url + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(list);
        return responseResult;
    }
}
